<template>
  <a-modal v-model:visible="modelVisible" :title="title" :width="600" :confirmLoading="confirmLoading"
    @cancel="handleCancel" @ok="handleOk" destroyOnClose>
    <a-form ref="formRef" :model="formData" :rules="rules" class="warehouse-form" :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }">
      <a-form-item label="编号" name="code">
        <a-input v-model:value="formData.code" placeholder="请输入编号" :disabled="isEdit" />
      </a-form-item>
      <a-form-item label="用户名" name="username">
        <a-input v-model:value="formData.username" placeholder="请输入用户名" />
      </a-form-item>
      <a-form-item label="姓名" name="name">
        <a-input v-model:value="formData.name" placeholder="请输入姓名" />
      </a-form-item>
      <a-form-item label="部门" name="department">
        <a-input v-model:value="formData.department" placeholder="请输入部门" />
      </a-form-item>
      <a-form-item label="通知人" name="notifier">
        <a-input v-model:value="formData.notifier" placeholder="请输入通知人，最多10人" :maxLength="100"
          @change="handleNotifierChange" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, computed, watch, nextTick } from 'vue';
import type { FormInstance } from 'ant-design-vue';
import { message } from 'ant-design-vue';

interface WarehouseData {
  id?: string;
  code: string;
  username: string;
  name: string;
  department: string;
  notifier: string;
}

export default defineComponent({
  name: 'WarehouseDialog',
  props: {
    id: {
      type: String,
      default: '',
    },
    visible: {
      type: Boolean,
      default: false,
    },
    currentRow: {
      type: Object as () => WarehouseData,
      default: () => ({
        code: '',
        username: '',
        name: '',
        department: '',
        notifier: '',
      }),
    },
  },
  emits: ['update:visible', 'success'],
  setup(props, { emit }) {
    const confirmLoading = ref(false);
    const formRef = ref<FormInstance>();
    const modelVisible = computed({
      get: () => props.visible,
      set: (val) => emit('update:visible', val),
    });

    const isEdit = computed(() => !!props.id);
    const title = computed(() => (isEdit.value ? '修改仓库' : '新增仓库'));

    const formData = reactive<WarehouseData>({
      code: '',
      username: '',
      name: '',
      department: '',
      notifier: '',
    });

    const rules = {
      code: [{ required: true, message: '请输入编号', trigger: 'blur' }],
      username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
      name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
      department: [{ required: true, message: '请输入部门', trigger: 'blur' }],
      notifier: [
        { required: true, message: '请输入通知人', trigger: 'blur' },
        {
          validator: (_, value) => {
            if (!value) return Promise.resolve();
            const count = value.split(/[,，]/).filter(item => !!item.trim()).length;
            return count <= 10
              ? Promise.resolve()
              : Promise.reject('通知人不能超过10人');
          }
        }
      ],
    };

    const resetForm = () => {
      Object.assign(formData, {
        code: '',
        username: '',
        name: '',
        department: '',
        notifier: '',
      });
      nextTick(() => {
        formRef.value?.resetFields();
      });
    };

    watch(
      () => props.visible,
      (newVal) => {
        if (newVal) {
          if (props.id) {
            // 编辑模式，使用传入的数据
            Object.keys(formData).forEach(key => {
              // console.log(key, props.currentRow[key]);
              formData[key] = props.currentRow[key];
            });
            // 确保表单验证状态重置
            nextTick(() => {
              formRef.value?.clearValidate();
            });
          } else {
            resetForm();
          }
        }
      },
      { immediate: true }
    );

    const handleCancel = () => {
      modelVisible.value = false;
      resetForm();
    };

    const handleOk = async () => {
      try {
        await formRef.value?.validate();
        confirmLoading.value = true;
        // TODO: 调用保存接口
        // const api = isEdit.value ? updateWarehouse : addWarehouse;
        // await api(formData);
        message.success(`${isEdit.value ? '修改' : '新增'}成功！`);
        modelVisible.value = false;
        resetForm();
        emit('success');
      } catch (error) {
        console.error('Failed to save warehouse:', error);
        message.error('提交失败，请检查输入或稍后重试');
      } finally {
        confirmLoading.value = false;
      }
    };

    const handleNotifierChange = (e: Event) => {
      const value = (e.target as HTMLInputElement).value;
      // 将中文逗号替换为英文逗号
      formData.notifier = value.replace(/，/g, ',');
    };

    return {
      modelVisible,
      confirmLoading,
      formRef,
      formData,
      rules,
      title,
      isEdit,
      handleCancel,
      handleOk,
      handleNotifierChange,
    };
  },
});
</script>

<style lang="less" scoped>
.warehouse-form {
  :deep(.a-form-item) {
    margin-bottom: 24px;
    width: 100% !important;

    .ant-input,
    .ant-select {
      width: 100%;
    }

    .ant-input {
      &::placeholder {
        color: rgba(0, 0, 0, 0.45);
      }
    }
  }

  :deep(.a-form-item:last-child) {
    margin-bottom: 0;
  }
}
</style>
